'''
@Project ：python-learn 
@File    ：4.5.py
@IDE     ：PyCharm 
@Author  ：计科2011-12-匡鑫
@Date    ：2024/9/19 14:45 
'''
import random
def main():
    students_filenpath = 'D:\code\python-learn\学生名单1（原始）.txt'
    new_students_filenpath = 'D:\code\python-learn\学生名单1（新）.txt'

    # 加载学生名单
    students = load_students(students_filenpath)

    # 随机选择并移除一个学生
    selected_student, remaining_students = remove(students)

    # 保存被选中的学生到新名单
    with open(new_students_filenpath, 'a', encoding='utf-8') as file:
        file.write(selected_student + '\n')

        # 如果名单为空，则不保存；否则，保存更新后的名单
    if remaining_students:
        save(remaining_students, students_filenpath)

        # 打印结果
    if selected_student:
        print(f"选择: {selected_student}")
    else:
        print("没有学生可以选择")
def load_students(filename):
    """从文件中加载学生名单"""
    with open(filename, 'r', encoding='utf-8') as file:
        students = file.read().splitlines()
    return students


def save(students, filename):
    """将学生名单保存到文件"""
    with open(filename, 'w', encoding='utf-8') as file:
        for student in students:
            file.write(student + '\n')


def remove(students):
    """随机选择一个学生，并从列表中移除"""
    if not students:
        return None, []
    selected_student = random.choice(students)
    remaining_students = [s for s in students if s != selected_student]
    return selected_student, remaining_students

if __name__ == "__main__":
    main()